package com.example.news.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.example.news.R;
import com.example.news.activity.WebActivity;
import com.example.news.adapter.NewsListAdapter;
import com.example.news.bean.NewsListJson;
import com.example.news.utils.ImageLoaderUtils;
import com.example.news.view.XListView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Administrator on 2016/5/17.
 */
public class ViewPagerFragment extends Fragment implements XListView.IXListViewListener {
    private XListView lv;
    private DisplayImageOptions options;
    private String path = "http://api.avatardata.cn/QiWenNews/Query?key=ac3badd7a5c2497d80b98559c57bf114&rows=10&page=";
    private int pages = 1;
    private NewsListAdapter adapter;
    ArrayList<NewsListJson.MyResult> list = new ArrayList<NewsListJson.MyResult>();
    ArrayList<NewsListJson.MyResult> listAll = new ArrayList<NewsListJson.MyResult>();
    Handler handler = new Handler();
    String mPath;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        //加载布局文件
        View view = inflater.inflate(R.layout.home_frag_content, null);
        //找控件
        lv = (XListView) view.findViewById(R.id.home_content_list);
        lv.setPullLoadEnable(true);

        lv.setXListViewListener(this);

        options = ImageLoaderUtils.initOptions();

        //获取文件缓存路径
        mPath = getActivity().getCacheDir().getPath();

        //得到网络数据
        getData(1);

        return view;
    }

    /*
     *  定义请求网络的方法
     */
    public void getData(final int page) {
        new Thread() {
            @Override
            public void run() {
                HttpUtils utils = new HttpUtils();
                utils.send(HttpRequest.HttpMethod.GET, path + page, new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException e, String s) {
                        try {
                            //从缓存目录中读取数据
                            ObjectInputStream os = new ObjectInputStream(new FileInputStream(mPath));
                            ArrayList<NewsListJson.MyResult> t = (ArrayList<NewsListJson.MyResult>) os.readObject();
                            //设置适配器
                            lv.setAdapter(new NewsListAdapter(getActivity(), t, options));

                            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();

                        } catch (Exception e1) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String json = responseInfo.result;

                        Gson gson = new Gson();
                        //解析json字符串
                        NewsListJson newsListJson = gson.fromJson(json, NewsListJson.class);
                        try {
                            //缓存首页数据(对象流)
                            //将第一次请求网络的数据缓存到内存中，方便下次没有网络的时候也可以正常显示
                            ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(mPath));
                            ArrayList<NewsListJson.MyResult> list = new ArrayList<NewsListJson.MyResult>();
                            list = newsListJson.result;
                            oo.writeObject(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        listAll = newsListJson.result;

                        list.addAll(listAll);
                        if (adapter == null) {
                            adapter = new NewsListAdapter(getActivity(), list, options);
                            //设置适配器
                            lv.setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();//刷新适配器
                        }

                        //设置条目点击监听
                        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                int index = position - 1;
                                //跳转到详情界面
                                Intent intent = new Intent(getActivity(), WebActivity.class);
                                intent.putExtra("url", list.get(index).url);
                                intent.putExtra("title", list.get(index).title);
                                startActivity(intent);
                            }
                        });
                    }
                });
            }
        }.start();
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.clear();//清空集合
                getData(1);
                onLoad();
            }
        }, 2000);
    }
    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages = pages + 1;
                getData(pages);
                adapter.notifyDataSetChanged();//刷新适配器
                onLoad();
            }
        }, 2000);
    }

    private void onLoad() {
        lv.stopRefresh();
        lv.stopLoadMore();
        //获取系统当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        String nowTime = format.format(new Date());
        lv.setRefreshTime(nowTime);
    }

}
